/**
 * 
 */
package org.cubikalabs.todolist.service;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cubikalabs.todolist.domain.Todo;
import org.cubikalabs.todolist.repository.ProjectRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.flex.messaging.MessageTemplate;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.userdetails.User;
import org.springframework.transaction.annotation.Transactional;

import flex.messaging.FlexContext;

/**
 * @author gflores
 *
 */
public class TodoServiceImpl implements TodoService {

	private final Log logger = LogFactory.getLog(getClass());

	@Autowired
	ProjectRepository repo;
	
	@Autowired
	MessageTemplate defaultMessageTemplate;

	public TodoServiceImpl() {
		super();
		logger.info("TodoServiceImpl");
	}

	@Override
	public Todo deleteTodo(Todo todo) {
		logger.info("deleteTodo");
		return null;
	}

	@Override
	@Transactional(readOnly = true)
	public List<Todo> getTodoList() {
		logger.info("getTodoList");
		return repo.getTodoList(getCurrentUserName());
	}

	@Override
	public Todo saveTodo(Todo todo) {
		logger.info("saveTodo");
		
		
		logger.debug(FlexContext.getUserPrincipal());
		
		todo.setUsername(getCurrentUserName());
		Todo save = repo.save(todo);
		
		defaultMessageTemplate.send("todolistUpdates", save);
		
		return save;
	}

	
	private String getCurrentUserName() {
		return ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
	}
}
